'''
Created on 04/03/2009

@author: eh01
'''
from dao.hubUserDAO import HubUserDAO
from exception.loginexception import LoginException
import base64
import logging
import md5

def loginRequired(func):
    def wrapper(self, *args, **kw):
        try:
            (username, password) = getUserCredentials(self.request)
            hubUserDAO = HubUserDAO()
            hubUser = hubUserDAO.getHubUserByUsername(username)
            # passwords are stored as a md5 hash
            if hubUser and md5.new(password).hexdigest() == hubUser.password:
                func(self, *args, **kw)
            else:
                raise LoginException("username and password invalid")
        except LoginException, e:
            self.response.clear()
            self.response.set_status(401, e.message)
            self.response.headers["WWW-Authenticate"] = 'Basic realm="eplanning.vic.au"'
    return wrapper

def adminLoginRequired(func):
    def wrapper(self, *args, **kw):
        try:
            (username, password) = getUserCredentials(self.request)
            hubUserDAO = HubUserDAO()
            hubUser = hubUserDAO.getHubUserByUsername(username)
            # passwords are stored as a md5 hash
            if hubUser and md5.new(password).hexdigest() == hubUser.password and hubUser.admin:
                func(self, *args, **kw)
            else:
                raise LoginException("username and password invalid")
        except LoginException, e:
            self.response.clear()
            self.response.set_status(401, e.message)
            self.response.headers["WWW-Authenticate"] = 'Basic realm="eplanning.vic.au"'
    return wrapper

def getUserCredentials(request):
    """ returns the user credentials from the http header """
    try:
        # the http header with the credentials
        authorization = request.headers["Authorization"]
        scheme, basic_credentials = authorization.split()
        # check the scheme is 'Basic' and that the credentials are present
        if (scheme == 'Basic') and (basic_credentials is not None):
            # decode the username and password
            user_pass = base64.b64decode(basic_credentials)
            username, password = user_pass.split(':')
            logging.info("Username and password supplied")
            return (username, password)
        else:
            raise LoginException("Failed to get credentials")
    except Exception:
        raise LoginException("Failed to get credentials")